package com.zhouxiaoge.dao;

import com.zhouxiaoge.entity.Permission;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.PreparedStatement;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-03-30 16:55
 */

public class PermissionDaoImpl extends JdbcDaoSupport implements PermissionDao {


    @Override
    public Permission createPermission(Permission permission) {
        final String sql = "INSERT  INTO sys_permissions(permission, description, available) VALUES(?,?,?)";
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(con -> {
            PreparedStatement preparedStatement = con.prepareStatement(sql, new String[]{"id"});
            preparedStatement.setString(1, permission.getPermission());
            preparedStatement.setString(2, permission.getDescription());
            preparedStatement.setBoolean(3, permission.getAvailable());
            return preparedStatement;
        }, keyHolder);
        permission.setId(keyHolder.getKey().longValue());

        return permission;
    }

    @Override
    public void deletePermission(Long permisssionId) {
        final String sql1 = "DELETE FROM sys_roles_permissions WHERE permission_id = ?";
        getJdbcTemplate().update(sql1, permisssionId);
        final String sql2 = "DELETE FROM sys_permissions WHERE id = ?";
        getJdbcTemplate().update(sql2, permisssionId);
    }
}
